package com.caiyouxi.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.caiyouxi.common.bean.ResData;
import com.caiyouxi.common.control.BaseController;
import com.caiyouxi.common.exception.ErrorCode;
import okhttp3.*;

import java.io.IOException;

/**
 * 发送HTTP请求
 *
 * @author weichangyong
 * @create 2017-10-25 14:46
 **/
public class HttpSendUtil extends BaseController
{
    public static final MediaType JSONTYPE = MediaType.parse("application/json; charset=utf-8");
    public static ResData post_body_json (String url, Object obj) {
        Log.d("==========send_url======:"+url,"obj:"+obj.toString());
        OkHttpClient okHttpClient = new OkHttpClient();
        ResData resData =null;
                //创建一个RequestBody(参数1：数据类型 参数2传递的json串)
        RequestBody requestBody = RequestBody.create(JSONTYPE, JSONObject.toJSON(obj).toString());
        //创建一个请求对象
        Request request = new Request.Builder().url(url).post(requestBody).build();
        //发送请求获取响应
        try {
            Response response=okHttpClient.newCall(request).execute();
            String response_body = response.body().string();
            Log.d("==========return_str======:"+response_body);
            //请在各自业务中处理相关业务逻辑，此处返回的与service返回的一样
            resData =  JSON.parseObject(response_body,ResData.class);
        } catch (IOException e) {
            e.printStackTrace();
            resData = failed(ErrorCode.SYS_FAIL.getCode(), ErrorCode.SYS_FAIL.getMsg());
        }

        return resData;

    }
}
